<?php

/**
 * @name UserController
 * @desc 用户控制器
 */
class UserController extends BaseController {

    const USER_STATUS = 1;
    const USER_INFO = '_USER_INFO';
    const IMAGE_URL = 'http://59.110.0.207:83';
    private $_userSvc;
    private $_novelSvc;

    public function init ()
    {
        parent::init ();
        $this->_userSvc = new Service_UserModel();
        $this->_novelSvc = new Service_NovelModel();
    }

    //登陆
    public function loginAction ()
    {
        if($this->isPost()){
            $mobile   = $this->_params->getMobile ();
            $password = $this->_params->getPassword();
            $info     = $this->_userSvc->verifyPhone ( $mobile );
            if( empty($info) ){
                echo parent::des_encode_msg( Tools_Response::ErrorEcho(ErrorCodeTool::ERROR_PGONE_NOT_REGISTER,ErrorCodeTool::getMsg(ErrorCodeTool::ERROR_PGONE_NOT_REGISTER)));
                exit();
            }
            if(!password_verify($password, $info['user_password'])){
                echo parent::des_encode_msg( Tools_Response::ErrorEcho(ErrorCodeTool::ERROR_PASSWORD, ErrorCodeTool::getMsg(ErrorCodeTool::ERROR_PASSWORD)));
                exit();
            }
            
            $ua       = $this->getUa();
            $loginData = [
                'user_id'       => $info['user_id'],
                'login_ip'      => $this->getIp(),
                'login_time'    => date('Y-m-d H:i:s'),
                'login_status'  => 1,
                'login_ua'      => $ua,
            ];
            $res = $this->_userSvc->addLog($loginData);
            if($res){
                $redis_tool = RedisTool::getInstance();
                $id = $info['user_id'];
                //生成token
                $sessionid   = md5($ua) . $id . 'LOGIN';
                setcookie( 'USELF' , base64_encode($sessionid) , time()+3600*24*7 , "/" , '' , false , true );
                $redis_tool->set( $sessionid , $id , 3600*24*7 );
                echo parent::des_encode_msg( Tools_Response::ErrorEcho(ErrorCodeTool::ERROR_SUCCESS, ErrorCodeTool::getMsg(ErrorCodeTool::ERROR_SUCCESS)));
                exit();
            }else{
                echo parent::des_encode_msg( Tools_Response::ErrorEcho(ErrorCodeTool::ERROR_LOGIN_FAILED, ErrorCodeTool::getMsg(ErrorCodeTool::ERROR_LOGIN_FAILED)));
                exit();
            }
        }else{
            $this->getView()->display('login/login.html');
        }
    }
    
    //退出登录
    public function logoutAction()
    {
        $id = $this->_params->getUserId();
        $uid = $this->checkLogin( $id );
        if( $uid ){
            setcookie( 'USELF' , NULL , time()-3600 , '/' , '' , false , true );
            $redis = RedisTool::getInstance();
            $redis->delete( md5($this->getUa()).$uid.'LOGIN' );
            $this->redirect( '../novel/novelHomePage' );
        }
    }

    //短信验证码
    public function getDynamicCodeAction()
    {
        if($this->isPost()){
            $ip       = $this->_params->getUserIp ();
            $mobile   = $this->_params->getMobile ();
            $scene   = $this->_params->getScene ();
            $now = date('Ymd');
            $redis    = RedisTool::getInstance();
            $code     = $redis->get( $mobile.'_code' );
            $ttl = $redis->ttl( $mobile.'_code');
            $phone_count = $redis->get($mobile.'_code_'.$now."_count");
            if($ttl >= 240){
                echo parent::des_encode_msg( Tools_Response::ErrorEcho(ErrorCodeTool::ERROR_CODE_TIME_LIMIT,  ErrorCodeTool::getMsg(ErrorCodeTool::ERROR_CODE_TIME_LIMIT)) );
                exit();
            }
            if($phone_count > 6){
                echo parent::des_encode_msg( Tools_Response::ErrorEcho(ErrorCodeTool::ERROR_CODE_PHONE_COUNT_LIMIT,  ErrorCodeTool::getMsg(ErrorCodeTool::ERROR_CODE_PHONE_COUNT_LIMIT)) );
                exit();
            }
            $res = $this->_userSvc->getDynamicCode( $ip, $mobile ,$scene);
            if( $res['code'] == 0 ){
                echo parent::des_encode_msg ( Tools_Response::ErrorEcho(ErrorCodeTool::ERROR_SUCCESS,  ErrorCodeTool::getMsg(ErrorCodeTool::ERROR_SUCCESS)) );
                exit();
            }else{
                echo parent::des_encode_msg ( Tools_Response::ErrorEcho(ErrorCodeTool::ERROR_CODE_SEND_FAILED,  ErrorCodeTool::getMsg(ErrorCodeTool::ERROR_CODE_SEND_FAILED)) );
                exit();
            } 
        }
    }
    
    //个人信息页
    public function getUserInfoAction()
    {
        $uid = $this->checkLogin();
        if(!$uid){
            //跳登录页面
            $this->redirect('login');
            exit();
        }
        $info = $this->_userSvc->getUserInfo( $uid );
        if( $info ){
            $info['address'] = $info['user_province'].($info['user_city'] != '' ? ','.$info['user_city'] : '').($info['user_city'] != '' ? ($info['user_area'] != '' ? ','.$info['user_area'] : '') : '');
            $info['user_img_url'] = $info['user_img_url'] != '' ? $info['user_img_url'] : '/public/img/images/my-head.png';
            $this->getView()->assign('data',$info);
            $this->getView()->display('user/personal.html');
        }else{
            echo parent::des_encode_msg( Tools_Response::Error ( 1 , '用户不存在' ) );
        }
    }
    
    //修改用户信息
    public function updateUserDataAction()
    {
        if($this->isPost()){
            $uid = $this->checkLogin();
            if(!$uid){
                //跳登录页面
                $this->redirect('login');
                exit();
            }
            $type = $this->_params->getUpdateType ();
            if( $type == 'address' ){
                $province = $this->_params->getProvince();
                $city     = $this->_params->getCity();
                $county   = $this->_params->getCounty();
                $data     = [ $province , $city , $county ];
            }else{
                $data = $this->_params->getUpdateData ();
            }
            $res  = $this->_userSvc->updateUser( $uid , $type , $data );
            if( $res ){
                echo parent::des_encode_msg( Tools_Response::Succ ( $res ) );
            }else{
                echo parent::des_encode_msg( Tools_Response::Error ( 1 , '修改用户信息失败' ) );
            }
        }
    }
    
    //我的书架
    public function myBookcaseAction()
    {
        $uid     = $this->_params->getUserId();
        $type    = $this->_params->getType();
//        $r = $this->checkLogin( $uid );
//        if(!$r){
//            //跳登录页面
//            $this->redirect('login');
//        }
//        $res['type'] = $type;
//        $res['uid'] = $uid;
        $records = $this->getRecord();
        if( $type == 1 ){
            $uid = $this->checkLogin();
            if(!$uid){
                $this->redirect('login');
                exit();
            }
            $res  = $this->_novelSvc->getUserBookCase( $uid , $records );
        }elseif( $type == 2 ){
            $res  = $this->_novelSvc->getUserReadRecord( $records );
        }
        $res['type'] = $type;
        $this->getView()->assign('data',$res);
        $this->getView()->display('user/bookcase.html');
    }
    
    //用户设置
    public function userSetAction()
    {
        if( $this->isPost() ){
            $uid = $this->checkLogin();
            if( $uid ){
                $back  = $this->_params->getBack();
                $size  = $this->_params->getSize();
                $style = $this->_params->getStyle();
                $res   = $this->_userSvc->editUserSet( $uid , $back , $size , $style );
                if( $res ){
                    echo parent::des_encode_msg( Tools_Response::Succ($res) );
                    exit();
                }else{
                    echo parent::des_encode_msg( Tools_Response::Error(1,'失败') );
                    exit();
                }
            }
            echo parent::des_encode_msg( Tools_Response::Error(1,'未登录') );
            exit();
        }
    }
    
    //用户消费记录
    public function myAccountAction()
    {
        $uid = $this->_params->getUserId();
        $user_id = $this->checkLogin( $uid );
        if( !$user_id ){
            $this->redirect('login');
            exit();
        }
        $user_info  = $this->_userSvc->getUserInfo( $user_id );
        $recharge   = $this->_userSvc->getUserRecharge( $user_id );
        $consume    = $this->_userSvc->getUserConsume( $user_id );
        $data['info']     = $user_info;
        $data['recharge'] = $recharge;
        $data['consume']  = $consume;
        $this->getView()->assign( 'data' , $data );
        $this->getView()->display( 'user/myAccount.html' );
    }
    
    //充值
    public function payforAction()
    {
        $this->getView()->display ( 'user/payfor.html' );
    }

    /**
     * 判断手机号是否注册
     */
    public function verifyPhoneAction(){
        if($this->isPost()){
            $mobile   = $this->_params->getMobile ();
            $type     = $this->_params->getType();
            if(!xs_is_mobilephone($mobile)){
                echo parent::des_encode_msg( Tools_Response::ErrorEcho(ErrorCodeTool::ERROR_PHONE_FOREMAT,ErrorCodeTool::getMsg(ErrorCodeTool::ERROR_PHONE_FOREMAT)) );
                exit();
            }
            $info     = $this->_userSvc->verifyPhone ( $mobile );
            if($type == '1'){
                if(empty($info) ){
                    echo parent::des_encode_msg( Tools_Response::ErrorEcho(ErrorCodeTool::ERROR_SUCCESS,ErrorCodeTool::getMsg(ErrorCodeTool::ERROR_SUCCESS)));
                    exit();
                }else{
                    echo parent::des_encode_msg( Tools_Response::ErrorEcho(ErrorCodeTool::ERROR_PHONE_HAS_REGISTERED,ErrorCodeTool::getMsg(ErrorCodeTool::ERROR_PHONE_HAS_REGISTERED)) );
                    exit();
                }
            }elseif($type == '2'){
                if(empty($info) ){
                    echo parent::des_encode_msg( Tools_Response::ErrorEcho(ErrorCodeTool::ERROR_PGONE_NOT_REGISTER,ErrorCodeTool::getMsg(ErrorCodeTool::ERROR_PGONE_NOT_REGISTER)));
                    exit();
                }else{
                    echo parent::des_encode_msg( Tools_Response::ErrorEcho(ErrorCodeTool::ERROR_SUCCESS,ErrorCodeTool::getMsg(ErrorCodeTool::ERROR_SUCCESS)));
                    exit();
                }
            }
        }else{
            echo parent::des_encode_msg( Tools_Response::ErrorEcho(ErrorCodeTool::ERROR_PHONE_NOT_EMOPTY,  ErrorCodeTool::getMsg(ErrorCodeTool::ERROR_PHONE_NOT_EMOPTY)) );
            exit();
        }
    }
    
    /**
     * 判断图片验证码是否正确
     */
    public function verifyImgCodeAction()
    {
        if($this->isPost()){
//            $mobile   = $this->_params->getMobile ();
            $imgCode = $this->_params->getImgCode ();
//            if(!xs_is_mobilephone($mobile)){
//                echo parent::des_encode_msg( Tools_Response::ErrorEcho(ErrorCodeTool::ERROR_PHONE_FOREMAT,ErrorCodeTool::getMsg(ErrorCodeTool::ERROR_PHONE_FOREMAT)) );
//                exit();
//            }
            if(empty($imgCode)){
                echo parent::des_encode_msg(Tools_Response::ErrorEcho(ErrorCodeTool::ERROR_IMG_CODE_NOT_EMPTY,ErrorCodeTool::getMsg(ErrorCodeTool::ERROR_IMG_CODE_NOT_EMPTY)) );
                exit();
            }
            $res  = $this->_userSvc->verifyImgCode ( $imgCode );
            if($res){
                echo parent::des_encode_msg( Tools_Response::ErrorEcho(ErrorCodeTool::ERROR_SUCCESS,ErrorCodeTool::getMsg(ErrorCodeTool::ERROR_SUCCESS)) );
                exit();
            }else{
                echo parent::des_encode_msg(Tools_Response::ErrorEcho(ErrorCodeTool::ERROR_IMG_CODE,ErrorCodeTool::getMsg(ErrorCodeTool::ERROR_IMG_CODE)) );
                exit();
            }
        }else{
            echo parent::des_encode_msg(  Tools_Response::ErrorEcho(ErrorCodeTool::ERROR_PARAM,ErrorCodeTool::getMsg(ErrorCodeTool::ERROR_PARAM)) );
            exit();
        }
    }
    
    public function codeAction(){
        $this->getView()->display( 'login/code.html' );
    }
    
    /**
     * 图片验证码
     * @return type
     */
     public function getImgCodeAction(){
        $this->_userSvc->getIImgCode ();
    }
    
    /**
     * 注册
     */
    public function registerAction()
    {
        if($this->isPost()){
            $mobile   = $this->_params->getMobile ();
            if(empty($mobile)){
                echo parent::des_encode_msg(Tools_Response::ErrorEcho(ErrorCodeTool::ERROR_PHONE_NOT_EMOPTY, ErrorCodeTool::getMsg(ErrorCodeTool::ERROR_PHONE_NOT_EMOPTY)) );
                exit();
            }
            if(!xs_is_mobilephone($mobile)){
                echo parent::des_encode_msg( Tools_Response::ErrorEcho(ErrorCodeTool::ERROR_PHONE_FOREMAT, ErrorCodeTool::getMsg(ErrorCodeTool::ERROR_PHONE_FOREMAT)) );
                exit();
            }
            $vcode    = $this->_params->getVcode ();
            $redis = RedisTool::getInstance();
            $code = $redis->get($mobile.'_code');
            if(empty($code) || ($vcode != $code)){
                echo parent::des_encode_msg( Tools_Response::ErrorEcho(ErrorCodeTool::ERROR_CODE,ErrorCodeTool::getMsg(ErrorCodeTool::ERROR_CODE)) );
                exit();
            }
            $password = $this->_params->getPassword();
            $rePassword = $this->_params->getRePassword();
//            $rePassword = '123456zxw';
            if ((strlen(strtolower($password)) < 6 ) || (strlen(strtolower($rePassword)) < 6)){
                echo parent::des_encode_msg( Tools_Response::ErrorEcho(ErrorCodeTool::ERROR_PASSWORD_LENTH_TOO_SMALL,ErrorCodeTool::getMsg(ErrorCodeTool::ERROR_PASSWORD_LENTH_TOO_SMALL)) );
                exit();
            }
            if ((strlen(strtolower($password)) > 18) || (strlen(strtolower($rePassword)) > 18)){
                echo parent::des_encode_msg( Tools_Response::ErrorEcho(ErrorCodeTool::ERROR_PASSWORD_LENTH_TOO_BIG,ErrorCodeTool::getMsg(ErrorCodeTool::ERROR_PASSWORD_LENTH_TOO_BIG)) );
                exit();
            }
            if (!check_password(strtolower($password)) || !check_password(strtolower($rePassword))){
                echo parent::des_encode_msg( Tools_Response::ErrorEcho(ErrorCodeTool::ERROR_PASSWORD_FORMAT, ErrorCodeTool::getMsg(ErrorCodeTool::ERROR_PASSWORD_FORMAT)) );
                exit();
            }
//            $ua         = $this->getUa();
            if($password != $rePassword){
                echo parent::des_encode_msg( Tools_Response::ErrorEcho(ErrorCodeTool::ERROR_TWICE_PWD_NOT_SAME, ErrorCodeTool::getMsg(ErrorCodeTool::ERROR_TWICE_PWD_NOT_SAME)) );
                exit();
            }
            $res = $this->_userSvc->register ( $mobile , $password );
            if($res){
                echo parent::des_encode_msg( Tools_Response::ErrorEcho(ErrorCodeTool::ERROR_SUCCESS, ErrorCodeTool::getMsg(ErrorCodeTool::ERROR_SUCCESS)) );
                exit();
            }else{
                echo parent::des_encode_msg( Tools_Response::ErrorEcho(ErrorCodeTool::ERROR_REGISTER_FAILED, ErrorCodeTool::getMsg(ErrorCodeTool::ERROR_REGISTER_FAILED)) );
                exit();
            }
        }else{
            $this->getView()->display( 'login/register.html' );
        }
    }
    
    
    /**
     * 忘记密码
     */
    public function retrieveAction (){
        if($this->isPost()){
//            $mobile = '1386696688';
            $mobile   = $this->_params->getMobile ();
            $info     = $this->_userSvc->verifyPhone ( $mobile );
            if(empty($info) ){
                echo parent::des_encode_msg( Tools_Response::ErrorEcho(ErrorCodeTool::ERROR_PGONE_NOT_REGISTER,ErrorCodeTool::getMsg(ErrorCodeTool::ERROR_PGONE_NOT_REGISTER)));
                exit();
            }
            $vcode    = $this->_params->getVcode ();
            $redis = RedisTool::getInstance();
            $code = $redis->get($mobile.'_code');
            if(empty($code) || ($vcode != $code)){
                echo parent::des_encode_msg( Tools_Response::ErrorEcho(ErrorCodeTool::ERROR_CODE, ErrorCodeTool::getMsg(ErrorCodeTool::ERROR_CODE)) );
                exit();
            }
            $now = time();
            $_SESSION['RETRIEVE'.$mobile]['mobile'] = $mobile;
            $_SESSION['RETRIEVE'.$mobile]['expire'] = $now;
            echo parent::des_encode_msg( Tools_Response::ErrorEcho(ErrorCodeTool::ERROR_SUCCESS, ErrorCodeTool::getMsg(ErrorCodeTool::ERROR_SUCCESS) , array('t'=> $mobile )) );
            exit();
        }else{
            $this->getView()->display('login/retrieve.html');
        }
    }

    /**
     * 修改密码
     */
    public function resetPasswordAction()
    {
        if($this->isPost()){
            $mobile   = $this->_params->getMobile ();
            if( !isset( $_SESSION['RETRIEVE'.$mobile] ) ){
                echo parent::des_encode_msg( Tools_Response::ErrorEcho(ErrorCodeTool::ERROR_PASSWORD_RESET_FAILED,ErrorCodeTool::getMsg(ErrorCodeTool::ERROR_PASSWORD_RESET_FAILED)));
                exit();
            }
            if( isset( $_SESSION['RETRIEVE'.$mobile]['expire']) && ( $_SESSION['RETRIEVE'.$mobile]['expire'] - time() ) > 300 ){
                echo parent::des_encode_msg( Tools_Response::ErrorEcho(ErrorCodeTool::ERROR_OPERATION_FAILED,ErrorCodeTool::getMsg(ErrorCodeTool::ERROR_OPERATION_FAILED)));
                exit();
            }
            $password = $this->_params->getPassword();
            $rePassword = $this->_params->getRePassword();
            $info     = $this->_userSvc->verifyPhone ( $mobile );
            if(empty($info) ){
                echo parent::des_encode_msg( Tools_Response::ErrorEcho(ErrorCodeTool::ERROR_PGONE_NOT_REGISTER,ErrorCodeTool::getMsg(ErrorCodeTool::ERROR_PGONE_NOT_REGISTER)));
                exit();
            }
            if (!check_password(strtolower($password)) || !check_password(strtolower($rePassword))){
                echo parent::des_encode_msg( Tools_Response::ErrorEcho(ErrorCodeTool::ERROR_PASSWORD_FORMAT, ErrorCodeTool::getMsg(ErrorCodeTool::ERROR_PASSWORD_FORMAT)) );
                exit();
            }
            if($password != $rePassword){
                echo parent::des_encode_msg( Tools_Response::ErrorEcho(ErrorCodeTool::ERROR_TWICE_PWD_NOT_SAME, ErrorCodeTool::getMsg(ErrorCodeTool::ERROR_TWICE_PWD_NOT_SAME)) );
                exit();
            }
            $res = $this->_userSvc->resetPassword ( $mobile , $password );
            if($res){
                echo parent::des_encode_msg( Tools_Response::ErrorEcho(ErrorCodeTool::ERROR_SUCCESS, ErrorCodeTool::getMsg(ErrorCodeTool::ERROR_SUCCESS)) );
                exit();
            }else{
                echo parent::des_encode_msg( Tools_Response::ErrorEcho(ErrorCodeTool::ERROR_PASSWORD_RESET_FAILED, ErrorCodeTool::getMsg(ErrorCodeTool::ERROR_PASSWORD_RESET_FAILED)) );
                exit();
            }
        }
        $t = $this->_params->getT();
        if(!$_SESSION['RETRIEVE'.$t]){
            $this->getView()->display( 'login/login.html' ); 
        }else{
            $this->getView()->assign('t',$t);
            $this->getView()->display( 'login/resetPassword.html' ); 
        }
    }
    
    /**
     * 协议
     */
    public function agreementAction()
    {
        $this->getView()->display( 'user/agreement.html' );
    }
    
    
    public function changePasswordAction(){
        if($this->isPost()){
            $password = $this->_params->getPassword();
            $newPassword = $this->_params->getNewRePassword();
            $newRePassword = $this->_params->getNewReRepassword();
            $uid = $this->checkLogin();
            if( !$uid ){
                echo parent::des_encode_msg( Tools_Response::ErrorEcho(ErrorCodeTool::ERROR_USER_NOT_LOGIN,ErrorCodeTool::getMsg(ErrorCodeTool::ERROR_USER_NOT_LOGIN)));
                exit();
            }
            $info     = $this->_userSvc->getUserPwd ( $uid );
            if(empty($info) ){
                echo parent::des_encode_msg( Tools_Response::ErrorEcho(ErrorCodeTool::ERROR_PGONE_NOT_REGISTER,ErrorCodeTool::getMsg(ErrorCodeTool::ERROR_PGONE_NOT_REGISTER)));
                exit();
            }
            if(!password_verify($password, $info['user_password'])){
                echo parent::des_encode_msg( Tools_Response::ErrorEcho(ErrorCodeTool::ERROR_PASSWORD, ErrorCodeTool::getMsg(ErrorCodeTool::ERROR_PASSWORD)));
                exit();
            }
            if (!check_password(strtolower($newPassword)) || !check_password(strtolower($newRePassword))){
                echo parent::des_encode_msg( Tools_Response::ErrorEcho(ErrorCodeTool::ERROR_PASSWORD_FORMAT, ErrorCodeTool::getMsg(ErrorCodeTool::ERROR_PASSWORD_FORMAT)) );
                exit();
            }
            if($newPassword != $newRePassword){
                echo parent::des_encode_msg( Tools_Response::ErrorEcho(ErrorCodeTool::ERROR_TWICE_PWD_NOT_SAME, ErrorCodeTool::getMsg(ErrorCodeTool::ERROR_TWICE_PWD_NOT_SAME)) );
                exit();
            }
            $res = $this->_userSvc->resetPasswordById ( $uid , $newPassword );
            if($res){
                setcookie( 'USELF' , NULL , time()-3600 , '/' , '' , false , true );
                $redis = RedisTool::getInstance();
                $redis->delete( md5($this->getUa()).$uid.'LOGIN' );
                echo parent::des_encode_msg( Tools_Response::ErrorEcho(ErrorCodeTool::ERROR_SUCCESS, ErrorCodeTool::getMsg(ErrorCodeTool::ERROR_SUCCESS)) );
                exit();
            }else{
                echo parent::des_encode_msg( Tools_Response::ErrorEcho(ErrorCodeTool::ERROR_PASSWORD_RESET_FAILED, ErrorCodeTool::getMsg(ErrorCodeTool::ERROR_PASSWORD_RESET_FAILED)) );
                exit();
            }
        }
        $this->getView()->display( 'user/changePassword.html' );
    }
    
    /**
     * 验证密码正确性
     */
    public function verifyPasswordAction(){
        if($this->isPost()){
            $uid = $this->checkLogin();
            if(!$uid){
               //跳登录页面
               echo parent::des_encode_msg( Tools_Response::ErrorEcho(ErrorCodeTool::ERROR_USER_NOT_LOGIN, ErrorCodeTool::getMsg(ErrorCodeTool::ERROR_USER_NOT_LOGIN)));
               exit();
            }
            $password = $this->_params->getPassword();
            $info = $this->_userSvc->getUserPwd( $uid );
            if(!password_verify($password, $info['user_password'])){
                echo parent::des_encode_msg( Tools_Response::ErrorEcho(ErrorCodeTool::ERROR_PASSWORD, ErrorCodeTool::getMsg(ErrorCodeTool::ERROR_PASSWORD)));
                exit();
            }else{
                echo parent::des_encode_msg( Tools_Response::ErrorEcho(ErrorCodeTool::ERROR_SUCCESS, ErrorCodeTool::getMsg(ErrorCodeTool::ERROR_SUCCESS)));
                exit();
            }
        }
//        $this->getView()->display( 'user/changePassword.html' );
    }
    
    
    
}
